package com.test.lyt.service.impl;

import com.test.lyt.entity.dto.FileDTO;
import com.test.lyt.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.*;

@Service
public class FileServiceImpl implements FileService {

    private static final String SLASH = "/";

    private static String fileDir = "F:/EasyFS/";
    @Override
    public int delete(FileDTO fileDTO) {
        return 0;
    }

    @Override
    public Map<String, Object> queryList(FileDTO fileDTO) {
        String dir = fileDTO.getDir();

        if (fileDir == null) {
            fileDir = SLASH;
        }
        if (!fileDir.endsWith(SLASH)) {
            fileDir += SLASH;
        }
        Map<String, Object> rs = new HashMap<>();
        if (dir == null || SLASH.equals(dir)) {
            dir = "";
        } else if (dir.startsWith(SLASH)) {
            dir = dir.substring(1);
        }
        File file = new File(fileDir + dir);
        File[] listFiles = file.listFiles();
        List<Map> dataList = new ArrayList<>();
        if (listFiles != null) {
            for (File f : listFiles) {
                if ("sm".equals(f.getName())) {
                    continue;
                }
                Map<String, Object> m = new HashMap<>(0);
                // 文件名称
                m.put( "name", f.getName() );
                // 修改时间
                m.put( "updateTime", f.lastModified() );
                // 是否是目录
                m.put( "isDir", f.isDirectory() );
                if (f.isDirectory()) {
                    // 文件类型
                    m.put( "type", "dir" );
                }
                dataList.add(m);
            }
        }
        // 根据上传时间排序
        Collections.sort(dataList, new Comparator<Map>() {
            @Override
            public int compare(Map o1, Map o2) {
                Long l1 = (long) o1.get("updateTime");
                Long l2 = (long) o2.get("updateTime");
                return l1.compareTo(l2);
            }
        });
        // 把文件夹排在前面
        Collections.sort(dataList, new Comparator<Map>() {
            @Override
            public int compare(Map o1, Map o2) {
                Boolean l1 = (boolean) o1.get("isDir");
                Boolean l2 = (boolean) o2.get("isDir");
                return l2.compareTo(l1);
            }
        });
        rs.put( "data", dataList );
        return rs;
    }
}
